﻿using MicroBlog.Areas.Admin.ViewModels;
using MicroBlog.Infrastructure;
using MicroBlog.Models;
using MicroBlog.Services;
using MicroBlog.ViewModels;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

namespace MicroBlog.Areas.Admin.Controllers
{
    public class BlogController : BaseController
    {
        private readonly AppSettings _appSettings;
        private readonly IBlogManager _blogManager;

        public BlogController(IOptions<AppSettings> options, IBlogManager blogManager)
        {
            _blogManager = blogManager;
            _appSettings = options.Value;
        }
        #region 返回视图
        /// <summary>
        /// 博客列表页
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 创建博客页
        /// </summary>
        /// <returns></returns>
        public IActionResult Create()
        {
            return View(_appSettings.UseMarkdown ? "Write" : "Create");
        }
        /// <summary>
        /// 编辑博客页
        /// </summary>
        /// <param name="id">博客ID</param>
        /// <returns></returns>
        public IActionResult Edit(int id)
        {
            ViewBag.Id = id;
            return View(_appSettings.UseMarkdown ? "Write" : "Create");
        }
        /// <summary>
        /// 标签管理页
        /// </summary>
        /// <returns></returns>
        public IActionResult Tags()
        {
            return View();
        }
        #endregion

        /// <summary>
        /// 根据关键字查询所有博客
        /// </summary>
        /// <param name="key"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetBlogs(string key, int pageIndex = 0, int pageSize = 25)
        {
            var filterExpression = ExpressionExtensions.True<Blog>();
            if (!string.IsNullOrEmpty(key))
            {
                filterExpression = filterExpression.And(p => p.Title.Contains(key));
            }
            var blogs = await _blogManager.SearchAsync(filterExpression, pageIndex, pageSize);
            return Json(blogs);
        }
        /// <summary>
        /// 获取博客的详细信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> GetBlog(int id)
        {
            var blog = id == 0 ? null : await _blogManager.FirstOrDefaultAsync(id);
            if (blog == null)
            {
                blog = CreateBlog();
            }
            else if (blog.BlogContent == null)
            {
                blog.BlogContent = new BlogContent();
            }
            return Json(blog);
        }
        /// <summary>
        /// 发布博客
        /// </summary>
        /// <param name="blog"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Post([FromBody] Blog blog)
        {
            var result = await _blogManager.WriteAsync(blog);
            return Json(result);
        }
        /// <summary>
        /// 删除博客
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> Delete(int id)
        {
            var result = await _blogManager.RemoveAsync(id);
            return Json(result);
        }
        /// <summary>
        /// 更新博客
        /// </summary>
        /// <param name="blog"></param>
        /// <returns></returns>
        public async Task<IActionResult> Update([FromBody] Blog blog)
        {
            var result = await _blogManager.UpdateAsync(blog);
            return Json(result);
        }

        /// <summary>
        /// 查看所有标签
        /// </summary>
        /// <returns></returns>
        public async Task<IList<TagViewModel>> GetTags()
        {
            return await _blogManager.GetTagsAsync();
        }
        /// <summary>
        /// 删除指定的标签
        /// </summary>
        /// <param name="name">标签</param>
        /// <returns></returns>
        public async Task<IActionResult> DeleteTag(string name)
        {
            var result = await _blogManager.RemoveTagAsync(name);
            return Json(result);
        }
        /// <summary>
        /// 更新指定的标签
        /// </summary>
        /// <param name="tag"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UpdateTag([FromBody] TagEditViewModel tag)
        {
            var result = await _blogManager.UpdateTagAsync(tag.Origin, tag.Name);
            return Json(result);
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="environment"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Upload([FromServices] IWebHostEnvironment environment)
        {
            List<UploadResult> list = new List<UploadResult>();
            var files = Request.Form.Files;
            string webRootPath = environment.WebRootPath;
            string contentRootPath = environment.ContentRootPath;
            foreach (var file in files)
            {
                if (file.Length > 0)
                {
                    var fileExt = Path.GetExtension(file.FileName);
                    var fileName = Guid.NewGuid().ToString() + fileExt;
                    var path = Path.Combine(environment.WebRootPath + "\\images\\upload", fileName);
                    using (var stream = new FileStream(path, FileMode.CreateNew))
                    {
                        await file.CopyToAsync(stream);
                        UploadResult img = new UploadResult
                        {
                            Name = fileName,
                            Url = @"/images/upload/" + fileName
                        };
                        list.Add(img);
                    }
                }
            }
            return new JsonResult(list);
        }
        private Blog CreateBlog()
        {
            return new Blog
            {
                BlogContent = new BlogContent(),
                Tags = new List<Tag>(),
                Created = DateTime.Now
            };
        }
    }
}